package dongze.com.ckdj.service.uploader;

import android.util.Log;

import dongze.com.ckdj.data.DataLayer;
import dongze.com.ckdj.map.MapUtil;
import dongze.com.ckdj.persistence.dao.DaoSession;
import dongze.com.ckdj.persistence.dao.NamePlateUploadRecord;
import dongze.com.ckdj.persistence.dao.NamePlateUploadRecordDao;
import dongze.com.ckdj.persistence.dao.ServerUploadTask;
import dongze.com.ckdj.util.MyLog;
import io.reactivex.ObservableEmitter;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DisposableObserver;

/**
 * Created by fanqwz on 2017/8/23.
 */

public class NamePlateUploader extends Uploader<String, String> {
    private static final String TAG = NamePlateUploader.class.getSimpleName();
    MapUtil mapUtil;
    String vin;
    String userNo;
    String imageIndex;

    public NamePlateUploader(Scheduler subscribeThread, Scheduler observerThread, ServerUploadTask task, MapUtil mapUtil, DataLayer dataLayer, DaoSession session, ImageUploader.ImageProgressListener listener) {
        super(AndroidSchedulers.mainThread(), observerThread);
        NamePlateUploadRecord record = session.getNamePlateUploadRecordDao().queryBuilder().where(
                NamePlateUploadRecordDao.Properties.Id.eq(task.getRecordId()))
                .uniqueOrThrow();
        this.mapUtil = mapUtil;
        this.vin = record.getVin();
        this.userNo = record.getUser();
        this.imageIndex = record.getImgIndex();

        dependsOn(new ImageUploader(subscribeThread,
                observerThread,
                dataLayer,
                session.getImageDao(),
                task.getImage(),
                listener));
    }

    @Override
    Worker<String, String> getWorker() {
        return worker;
    }

    Worker<String, String> worker = new Worker<String, String>() {
        String img;
        @Override
        public void accept(String depends) {
            img = depends;
        }

        @Override
        public void doWork(final ObservableEmitter<String> e) {
            MyLog.d(TAG, "doWork: id="+ imageIndex + ",image=" + img);
            mapUtil.uploadNamePlate(vin, imageIndex, img, userNo, new DisposableObserver<String>() {
                @Override
                public void onNext(String value) {
                    e.onNext(value);
                }

                @Override
                public void onError(Throwable ex) {
                    e.onError(ex);
                }

                @Override
                public void onComplete() {
                    e.onComplete();
                }
            });
        }
    };
}
